import request from "../request"
import rsa from "../rsa";
import cryptoJs from "../cryptoJs";
import axios from "axios";
import { createRouter, createWebHistory } from 'vue-router';
// 引入element-plus的notify和message
import { ElNotification, ElMessage } from "element-plus";

let router = createRouter({
    history: createWebHistory(),
    routes: []
});
/**
 * 设置服务端公钥
 */
let setServerPublicKey = function (publicKey) {
    localStorage.setItem("serverPublicKey", publicKey);
}

/**
 * 获取服务端公钥
 */
let getServerPublicKey = () => {
    return localStorage.getItem("serverPublicKey");
}

/**
 * 获取请求地址
 */
let getRequestUrl = function (options) {
    // 获取根地址
    let rootAddress = request.getRootAddress();
    // 如果是/结尾，则去掉结尾
    if (rootAddress.endsWith("/")) {
        rootAddress = rootAddress.substring(0, rootAddress.length - 1);
    }

    // 获取uri
    let uri = options.uri;
    // 如果uri是/开头，则去掉开头
    if (uri.startsWith("/")) {
        uri = options.uri.substring(1);
    }

    return rootAddress + "/security/request/simpleForward/" + uri;
}

/**
 * 生成客户端密钥
 */
let generateClientKey = function () {
    let arr = [
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
    ];
    let clientKey = "";
    for (let i = 0; i < 32; i++) {
        clientKey += arr[Math.floor(Math.random() * arr.length)];
    }
    localStorage.setItem("clientKey", clientKey);
    return clientKey;
}

/**
 * 获取客户端密钥
 */
let getClientKey = function () {
    return localStorage.getItem("clientKey");
}


/**
 * 清空客戶端密钥和服务端公钥
 */
let clearKey = function () {
    localStorage.removeItem("clientKey");
    localStorage.removeItem("serverPublicKey");
}


/**
 * 生成content
 * @param options
 */
let getContent = function (options) {
    // 获取服务端传来的公钥
    let serverPublicKey = getServerPublicKey();
    // 将options.data加密
    let encryptStr = rsa.encrypt(serverPublicKey, JSON.stringify(options.data));
    let clientKey = getClientKey();
    if (!clientKey) {
        clientKey = generateClientKey();
    }
    // 获取加密后的clientKey
    let clientKeyRsa = rsa.encrypt(serverPublicKey, clientKey);
    // 分为三个.分割，第一个是后端生成的公钥，第二个前端加密后的请求体，第三个是客户端生成的公钥
    return serverPublicKey + "." + encryptStr + "." + clientKeyRsa;
}


let send = async (options) => {
    // 如果没有isJumpLogin，则设置为true
    if (options.isJumpLogin === undefined||options.isJumpLogin === null) {
        options.isJumpLogin = true;
    }

    setTimeout(async ()=>{

        if (!options.data) {
            // 给options.data赋值，防止options.data为null
            options.data = {};
        }

        // 获取服务端传来的公钥
        let serverPublicKey = getServerPublicKey();
        if (!serverPublicKey) {

            await new Promise((resolve) => {
                // 向服务端请求公钥
                request.send({
                    uri: "/security/request/getNewPublicKey",
                    stateSuccess: (res) => {
                        setServerPublicKey(res.data);
                        resolve();
                    }
                });
            });
        }

        axios({
            url: getRequestUrl(options),
            method: "POST",
            data: {
                content: getContent(options)
            },
            headers: {
                token: request.getToken(),
                languageCode: request.getLanguageCode(),
                ...options.header,
            }
        }).then((res) => {
            let data = res.data;
            if (!data.success) {

                // 如果安全保障过期，则重新请求安全保障
                if (data.stateCode === "securityExpire") {
                    console.log("安全保障过期，重新请求安全保障");
                    // 清空客户端密钥和服务端公钥
                    clearKey();
                    // 清空前端生成的密钥
                    send(options);
                    return;
                }

                // 如果请求安全验证过期，则重新请求请求安全验证
                if (data.stateCode === "securityRequestIsExpired") {
                    console.log("请求安全验证过期，重新请求安全验证");
                    // 清空客户端密钥和服务端公钥
                    clearKey();
                    // 重新请求服务端公钥
                    send(options);
                    return;
                }

                // 如果服务端公钥错误，则重新请求服务端公钥
                if (data.stateCode === "publicKeyError") {
                    console.log("服务端公钥错误，重新请求服务端公钥");
                    // 清空客户端密钥
                    clearKey();
                    // 重新请求服务端公钥
                    send(options);
                    return;
                }

                if (data.stateCode === "securityRisk") {
                    console.error("安全风险，请求终止");
                    // 清空客户端密钥和服务端公钥
                    clearKey();

                    ElMessage({
                        message:data.errMsg,
                        type: "error"
                    });

                    setTimeout(() => {
                        router.push({
                            path: "/login/body"
                        }).then(() => {
                            // 刷新页面
                            window.location.reload();
                        });
                    },1000);
                    return;
                }

                options?.stateFail(data);
                return;
            }

            // AES解密data.data
            let decryptData = cryptoJs.decryptData(data.data, getClientKey());
            let json = JSON.parse(decryptData);

            console.debug("URI：\n", options.uri, "\n\n",
                "请求数据：\n", options.data, "\n\n",
                "原始数据：\n", data, "\n\n",
                "解密后的数据：\n", JSON.stringify(json)
            );

            // 如果未登录，则跳转到登录页面
            if (json.stateCode === "notLogin"&&options.isJumpLogin){
                console.log("未登录，跳转到登录页面");
                // 清空客户端密钥和服务端公钥
                clearKey();

                // 提示未登录
                // ElMessage({
                //     message: json.errMsg,
                //     type: "warning"
                // });

                setTimeout(()=>{
                    // 跳转到登录页面
                    router.push({
                        path: "/login/body"
                    }).then(() => {
                        // 刷新页面
                        window.location.reload();
                    })
                },1000);

                return;

            }

            // 如果stateCode为SUCCESS，则调用options.stateSuccess
            if (json.success && options?.stateSuccess) {
                options?.stateSuccess(json);
                return;
            }
            if (options?.stateFail) {
                options?.stateFail(json);
            }
        }).catch((err) => {
            if (err.message.startsWith("Network Error")) {
                console.error("网络请求失败，请检查网络连接");
                options?.stateFail({
                    success: false,
                    errMsg: "网络请求失败，请检查网络连接",
                    msgDictCode: "networkError",
                    operationCode: null,
                    state: 3000,
                    stateCode: "networkError"
                });
            }
        });

    },0);

}

export default {
    clearKey,
    setServerPublicKey,
    getServerPublicKey,
    send
}